import React, { forwardRef, useRef, useImperativeHandle } from 'react';

// 使用 forwardRef 创建一个可接收 ref 的函数组件
const CustomInput = forwardRef((props, ref) => {
  const inputRef = useRef(null);

  // 使用 useImperativeHandle 自定义暴露给父组件的实例值
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    },
    getValue: () => {
      return inputRef.current.value;
    },
  }));

  return (
    <input ref={inputRef} type="text" placeholder="Custom Input" {...props} />
  );
});

const ParentComponent = () => {
  const customInputRef = React.createRef();

  const focusCustomInput = () => {
    customInputRef.current.focus();
  };

  const getCustomInputValue = () => {
    const value = customInputRef.current.getValue();
    alert(`输入框的值是: ${value}`);
  };

  return (
    <div>
      <CustomInput ref={customInputRef} />
      <button onClick={focusCustomInput}>聚焦自定义输入框</button>
      <button onClick={getCustomInputValue}>获取输入框的值</button>
    </div>
  );
};

export default ParentComponent;
